//
//  HMUserAccountViewModel.swift
//  Weibo
//
//  Created by 吴少飞 on 16/9/22.
//  Copyright © 2016年 wushaofei. All rights reserved.
//

import UIKit

class HMUserAccountViewModel: NSObject {

    //单例全局访问点
    
    static let sharedUserAccountViewModel:HMUserAccountViewModel = HMUserAccountViewModel()
    
    var userAccount:HMUserAccount?{
        
        
        return HMUserAccount.loadUserAccount()
    }
    
    var isLogin :Bool{
        return accessToken != nil
    }
    
    var accessToken : String? {
        
        let token = userAccount?.access_token
        
        let expiresDate = userAccount?.expiresDate
        
        if let t = token {
            
            if expiresDate?.compare(Date()) == .orderedDescending {
                
                return t
            }else{
                return nil
            }
            
        }else{
            return nil
        }

    }
    
    
    func requestAccessToken(code:String,callBack: @escaping (Bool)->()){
        
        
        HMNetworkTools.sharedTools.requestAccessToken(code: code) { (response, error) in
            
            if error != nil{
                
//                print("网络异常\(error)")
                callBack(false)
            }
            
            guard let dict = response as?[String:Any] else {
                
                callBack(false)
                return
            }
            
            let userAccount = HMUserAccount(dict: dict)
            
            self.requestUserInfo(userAccount: userAccount,callBack: callBack)
        }
        
        
    }
    
    func requestUserInfo(userAccount:HMUserAccount,callBack: @escaping (Bool)->()) -> Void {
        
        HMNetworkTools.sharedTools.requestUserInfo(accessToken: userAccount.access_token!, uid: userAccount.uid) { (response, error) in
            
            if error != nil {
                
                print(error)
                callBack(false)
                return
            }
            guard let dict = response as? [String:Any] else{
                
                callBack(false)
                return
            }
            let name = dict["name"]
            
            let avatar_large = dict["avatar_large"]
            
            userAccount.name = name as? String
            userAccount.avatar_large = avatar_large as? String
            
            //登录成功 保存用户信息
            userAccount.saveUserAccount()
            callBack(true)
        }
        
    }

}
